//
//  AppDelegate.m
//  Learn
//
//  Created by icomexe on 2018/10/24.
//  Copyright © 2018年 cjg. All rights reserved.

#import "AppDelegate.h"
#import "BaseTabBarController.h"
#import "LoginViewController.h"
#import <UserNotifications/UserNotifications.h> //ios10以后的本地推送框架
#import "MineAPIManager.h"
#import <AFNetworking/AFHTTPSessionManager.h>
#import "MJTabBarController.h"
#import "BaseNavigationViewController.h"

#import <UserNotifications/UserNotifications.h> //ios10以后的本地推送框架
#import "IFlyMSC/IFlyMSC.h"
#import "Definition.h"


@interface AppDelegate ()<UNUserNotificationCenterDelegate>
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] init];
    self.window.rootViewController = [UIViewController new];
    [self.window makeKeyAndVisible];
    if (USER_DEFAULTS_VALUE_FOR_KEY(ProtectColorSwitch)) {
        self.is_eyeshield = [USER_DEFAULTS_VALUE_FOR_KEY(ProtectColorSwitch) boolValue];
        [self turnOrOffProtectColor];
    }
    if (self.useModel) {
        [self goHome];
       
    }else{
        [self goLogin];
    }
   
   

    
    [self requstLocalNotification];
    
    // 界面的跳转(针对应用程序被杀死的状态下的跳转)--- app杀死后点击通知进入app
    if (launchOptions[UIApplicationLaunchOptionsLocalNotificationKey]) { //点击通知开启app的情况 ，不区分iOS10之前或之后，同时也会走iOS10的通知代理。
        // 跳转代码
        UILabel *redView = [[UILabel alloc] init];
        redView.frame = CGRectMake(0, 200, SCREEN_W, 100);
        redView.text = @"app杀死后点击通知进入app";
        redView.backgroundColor = [UIColor redColor];
        [self.window.rootViewController.view addSubview:redView];
    }
    
    [self configureIFlySDK];

    

    return YES;
}
- (void)goHome
{
    // self.window.rootViewController = [[MJTabBarController alloc] init];
    self.window.rootViewController = [[BaseNavigationController alloc] initWithRootViewController:[[MJTabBarController alloc] init]];
    [self.window makeKeyAndVisible];
}
- (void)goLogin
{
    USER_DEFAULTS_REMOVE_OBJECT_FOR_KEY(USER_LOGIN_INFO);
    BaseNavigationController *nav = [[BaseNavigationController alloc] initWithRootViewController:[[LoginViewController alloc] init]];
    self.window.rootViewController = nav;
    [self.window makeKeyAndVisible];
}
- (UserInfoModel *)useModel
{
    if (VALIDICTIONARY(USER_DEFAULTS_VALUE_FOR_KEY(USER_LOGIN_INFO))) {
        USER_DEFAULTS_REMOVE_OBJECT_FOR_KEY(USER_LOGIN_INFO);
    }
    NSString *jsonString = USER_DEFAULTS_VALUE_FOR_KEY(USER_LOGIN_INFO);
    NSDictionary *dictionary = nil;
    if (jsonString.length > 0) {
        NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
        NSError *error = nil;
        dictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
         
    }
    if(dictionary)
    {
        return [UserInfoModel modelWithDictionary:dictionary];
    }
    return nil;
    
}
- (BOOL)isVip
{
    //return YES;
    return _isVip;
}
- (void)turnOrOffProtectColor
{
    if (lApp.is_eyeshield) {
        
        //获取RGBA颜色数值
            CGFloat r,g,b,a;
            [rgba(255, 183, 113, 1) getRed:&r green:&g blue:&b alpha:&a];
            //创建滤镜
            id cls = NSClassFromString(@"CAFilter");
            id filter = [cls filterWithName:@"colorMonochrome"];
            //设置滤镜参数
            [filter setValue:@[@(r),@(g),@(b),@(a)] forKey:@"inputColor"];
            [filter setValue:@(0.1) forKey:@"inputBias"];
            [filter setValue:@(0.8) forKey:@"inputAmount"];
        lApp.window.layer.filters = [NSArray arrayWithObject:filter];
    }else{
        lApp.window.layer.filters = [NSArray new];
    }
}

// 配置讯飞SDK
- (void)configureIFlySDK {
    //Set log level
    [IFlySetting setLogFile:LVL_ALL];
    
    //Set whether to output log messages in Xcode console
    [IFlySetting showLogcat:YES];

    //Set the local storage path of SDK
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [paths objectAtIndex:0];
    [IFlySetting setLogFilePath:cachePath];
    
    //Set APPID
    NSString *initString = [[NSString alloc] initWithFormat:@"appid=%@",APPID_VALUE];
    
    //Configure and initialize iflytek services.(This interface must been invoked in application:didFinishLaunchingWithOptions:)
    [IFlySpeechUtility createUtility:initString];
}

//创建本地推送
- (void)requstLocalNotification {
    
    if (@available(iOS 10.0, *)) {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        //iOS 10 使用以下方法注册，才能得到授权，注册通知以后，会自动注册 deviceToken，如果获取不到 deviceToken，Xcode8下要注意开启 Capability->Push Notification。
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound)
                              completionHandler:^(BOOL granted, NSError * _Nullable error) {
                                  NSLog(@"授权本地推送通知");
                              }];
        //获取当前的通知设置，UNNotificationSettings 是只读对象，不能直接修改，只能通过以下方法获取
        [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
            NSLog(@"获取当前通知的设置");
        }];
    } else {
        if (MODEL_VERSION >= 8.0) {
            //设置通知的弹框类型- 声音提示、图标数字等
            UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:nil];
            //授权通知
            [[UIApplication sharedApplication] registerUserNotificationSettings:setting];
        }
    }
}
/*
 应用程序在进入前台,或者在前台的时候都会执行该方法 ---- app在后台挂着时点击通知进入app的操作
 */
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    NSLog(@"didReceiveLocalNotification");
    // 针对应用程序在后台的时候进行的跳转
    if (application.applicationState == UIApplicationStateInactive) {
        NSLog(@"进行界面的跳转");
        NSLog(@"%@", notification.userInfo);
        
        UILabel *redView = [[UILabel alloc] init];
        redView.frame = CGRectMake(0, 0, SCREEN_W, 100);
        redView.text = @"didReceiveLocalNotification";
        redView.backgroundColor = [UIColor redColor];
        [self.window.rootViewController.view addSubview:redView];
    }
}

#pragma mark -- 本地推送代理方法 -- iOS10后推送代理方法
//在展示通知前进行处理，即有机会在展示通知前再修改通知内容。
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler API_AVAILABLE(ios(10.0)){
    
    UILabel *redView = [[UILabel alloc] init];
    redView.frame = CGRectMake(0, 0, SCREEN_W, 100);
    redView.text = @"通知代理：willPresentNotification";
    redView.backgroundColor = [UIColor redColor];
    [self.window.rootViewController.view addSubview:redView];

    //1. 处理通知
    NSLog(@"在展示通知前进行处理，即有机会在展示通知前再修改通知内容");
    //2. 处理完成后条用 completionHandler ，用于指示在前台显示通知的形式
    if (@available(iOS 10.0, *)) {
        completionHandler(UNNotificationPresentationOptionAlert);
    } else {
        // Fallback on earlier versions
    }
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler  API_AVAILABLE(ios(10.0)){
    NSLog(@"消息推送代理方法didReceiveNotificationResponse = %@",response);
    UILabel *redView = [[UILabel alloc] init];
    redView.frame = CGRectMake(0, 0, SCREEN_W, 100);
    redView.text = @"通知代理didReceiveNotificationResponse";
    redView.backgroundColor = [UIColor redColor];
    [self.window.rootViewController.view addSubview:redView];
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(nullable UNNotification *)notification  API_AVAILABLE(ios(10.0)){
    NSLog(@"消息推送代理方法openSettingsForNotification = %@",notification);
    UILabel *redView = [[UILabel alloc] init];
    redView.frame = CGRectMake(0, 0, SCREEN_W, 100);
    redView.text = @"通知代理：openSettingsForNotification";
    redView.backgroundColor = [UIColor redColor];
    [self.window.rootViewController.view addSubview:redView];
}
#pragma mark -- appdelegate方法
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

//app进入前台 --- 将应用程序图标的数字取消
- (void)applicationWillEnterForeground:(UIApplication *)application {
    //设置应用程序图片右上角的数字(如果想要取消右上角的数字, 直接把这个参数值为0)
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
